<?php
/*
 * 发布时候加载的文件, 现在使用seajs 进行加载
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 695f75997be97c7b7351086e5d7f0488beb46018 $
 * @time       14-2-7 上午10:28
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * destoon的样式选择器
 * @param $name             input 的 name
 * @param string $value     input 的 默认值
 * @return string
 */
function dstyle($name, $value = '') {
	global $destoon_style_id;
	$style = $color = '';
	if(preg_match("/^#[0-9a-zA-Z]{6}$/", $value)) $color = $value;
	if(!$destoon_style_id) {
		$destoon_style_id = 1;
		$style .= '<script type="text/javascript" src="'.SITE_URL.'file/script/color.js"></script>';
	} else {
		$destoon_style_id++;
	}
	$style .= '<input type="hidden" name="'.$name.'" id="color_input_'.$destoon_style_id.'" value="'.$color.'"/><img src="'.SITE_URL.'file/image/color.gif" width="21" height="18" align="absmiddle" id="color_img_'.$destoon_style_id.'" style="cursor:pointer;background:'.$color.'" onclick="color_show('.$destoon_style_id.', Dd(\'color_input_'.$destoon_style_id.'\').value, this);"/>';
	return $style;
}

/**
 * dt 的日期选择器
 * @param $name             input的名称
 * @param string $value     默认值, 默认为 ''
 * @param string $sep       日期之间的分隔符, 默认为 '-'
 * @return string           input选择字串
 */
function dcalendar($name, $value = '', $sep = '-') {
	global $destoon_calendar_id;
	$calendar = '';
	$id = str_replace(array('[', ']'), array('', ''), $name);
	if(!$destoon_calendar_id) {
		$destoon_calendar_id = 1;
		$calendar .= '<script type="text/javascript" src="'.SITE_URL.'file/script/calendar.js"></script>';
	}
	$calendar .= '<input type="text" name="'.$name.'" id="'.$id.'" value="'.$value.'" size="10" onfocus="ca_show(\''.$id.'\', this, \''.$sep.'\');" readonly ondblclick="this.value=\'\';"/> <img src="'.SITE_URL.'file/image/calendar.gif" align="absmiddle" onclick="ca_show(\''.$id.'\', this, \''.$sep.'\');" style="cursor:pointer;"/>';
	return $calendar;
}

/**
 * 文章发布的选择项
 * @param $sarray array     option数组
 * @param $name   string    form识别name
 * @param string $title     默认显示的第一位
 * @param int $selected     选择项目
 * @param string $extend    扩展,例如id
 * @param int $key          是否使用键作为value值
 * @param string $ov        默认的option value
 * @param int $abs          未知
 * @return string
 */
function dselect($sarray, $name, $title = '', $selected = 0, $extend = '', $key = 1, $ov = '', $abs = 0) {
	$select = '<select name="'.$name.'" '.$extend.'>';
	if($title) $select .= '<option value="'.$ov.'">'.$title.'</option>';
	foreach($sarray as $k=>$v) {
		if(!$v) continue;
        $_selected = ($abs ? ($key ? $k : $v) === $selected : ($key ? $k : $v) == $selected) ? ' selected=selected' : '';
		$select .= '<option value="'.($key ? $k : $v).'"'.$_selected.'>'.$v.'</option>';
	}	
	$select .= '</select>';
	return $select;
}

/**
 * 同上 Author gengshuai
 * @param $sarray
 * @param $name
 * @param string $title
 * @param int $selected
 * @param string $extend
 * @param int $key
 * @param string $ov
 * @param int $abs
 * @return string
 */
function dselect_choose($sarray, $name, $title = '', $selected = 0, $extend = '', $key = 1, $ov = '', $abs = 0) {
	$select = '<select onChange="GoAndChang('."'".$name."'".','.'this.value'.');" name="'.$name.'" '.$extend.'>';
	foreach($sarray as $k=>$v) {
		if(!$v) continue;
		$_selected = ($abs ? ($key ? $k : $v) === $selected : ($key ? $k : $v) == $selected) ? ' selected=selected' : '';
		if(($key ? $k : $v)==0){
			$select .= '<option value="'.($key ? $k : $v).'"'.$_selected.'>'.$title.'</option>';
		}else{
			$select .= '<option value="'.($key ? $k : $v).'"'.$_selected.'>'.$v.'</option>';
		}
	}
	$select .= '</select>';
	return $select;
}

/**
 * checkbox
 * @param        $sarray
 * @param        $name
 * @param string $checked
 * @param string $extend
 * @param int    $key
 * @param string $except
 * @param int    $abs
 * @return string
 */
function dcheckbox($sarray, $name, $checked = '', $extend = '', $key = 1, $except = '', $abs = 0) {
	$checked = $checked ? explode(',', $checked) : array();
	$except = $except ? explode(',', $except) : array();
	$checkbox = $sp = '';
	foreach($sarray as $k=>$v) {
		if(in_array($key ? $k : $v, $except)) continue;
		$sp = in_array($key ? $k : $v, $checked) ? ' checked ' : '';
		$checkbox .= '<input type="checkbox" name="'.$name.'" value="'.($key ? $k : $v).'"'.$sp.$extend.'> '.$v.'&nbsp;';
	}
	return $checkbox;
}

/**
 * 类别选择器
 * @param       $cats
 * @param       $extend
 * @param array $eqs
 * @author      Mark
 */
function xdCatCheckbox($cats, $extend, $eqs = array()) {
	$checkbox  = '';
	foreach($cats as $k => $cat) {
		$checked = (isset($eqs) && in_array($cat['catid'], $eqs)) ? " checked='checked' " : '';
		$checkbox .= "<span class='nowrap'><input type='checkbox' {$extend} value='{$cat['catid']}' {$checked} /> {$cat['catname']} &nbsp;</span>";
	}
	echo $checkbox;
}

/**
 * 类型选择
 * @param        $item
 * @param int    $cache
 * @param string $name
 * @param string $title
 * @param int    $typeid
 * @param string $extend
 * @param string $all
 * @return string
 */
function type_select($item, $cache = 0, $name = 'typeid', $title = '', $typeid = 0, $extend = '', $all = '') {
	$TYPE = get_type($item, $cache);
	$select = '<select name="'.$name.'" '.$extend.'>';
	if($all) $select .= '<option value="-1"'.($typeid == -1 ? ' selected=selected' : '').'>'.$all.'</option>';
	if($title) $select .= '<option value="0"'.($typeid == 0 ? ' selected=selected' : '').'>'.$title.'</option>';
	foreach($TYPE as $k=>$v) {
		$select .= ' <option value="'.$k.'"'.($k == $typeid ? ' selected' : '').'> '.$v['typename'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 编辑器选择
 * @param $name
 * @param $editor
 */
function editor_select($name, $editor) {
	$editors = array(
		'Default' => '全部',
		'Destoon' => '精简',
		'Simple'  => '简洁',
		'Basic'   => '基础',
	);
	$select = '<select name="'.$name.'>';
	foreach($editors as $k=>$v) {
		$select .= ' <option value="'.$k.'"'.($k == $editor ? ' selected="selected"' : '').'> '.$v.'</option>';
	}
	$select .= '</select>';
	return $select;

}


/**
 * url选择
 * @param        $name
 * @param string $ext
 * @param string $type
 * @param int    $urlid
 * @param string $extend
 * @return string
 */
function url_select($name, $ext = 'htm', $type = 'list', $urlid = 0, $extend = '') {
	global $L;
	include DT_ROOT."/api/url.inc.php";
	$select = '<select name="'.$name.'" '.$extend.'>';
	$types = count($urls[$ext][$type]);
	for($i = 0; $i < $types; $i++) {
		$select .= ' <option value="'.$i.'"'.($i == $urlid ? ' selected' : '').'>'.$L['url_eg'].' '.$urls[$ext][$type][$i]['example'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 模版选择器
 * @param string $file
 * @param string $module
 * @param string $name
 * @param string $title
 * @param string $template
 * @param string $extend
 * @return string
 */
function tpl_select($file = 'index', $module = '', $name = 'template', $title = '', $template = '', $extend = '') {
	include load('include.lang');
	global $CFG, $destoon_tpl_id;
	if(!$destoon_tpl_id) {
		$destoon_tpl_id = 1;
	} else {
		$destoon_tpl_id++;
	}
    $tpldir = $module ? DT_ROOT."/".$CFG['refactorTpl'] ."/".$module : DT_ROOT."/".$CFG['refactorTpl'] ;
	@include $tpldir."/these.name.php";
	$select = '<span id="destoon_template_'.$destoon_tpl_id.'"><select name="'.$name.'" '.$extend.'><option value="">'.$title.'</option>';
	$files = glob($tpldir."/*.htm");
	foreach($files as $tplfile)	{
		$tplfile = basename($tplfile);
		$tpl = str_replace('.htm', '', $tplfile);
		if(preg_match("/^".$file."-(.*)/i", $tpl) || !$file) {//$file == $tpl || 
			$selected = ($template && $tpl == $template) ? 'selected' : '';
            $templatename = (isset($names[$tpl]) && $names[$tpl]) ? $names[$tpl] : $tpl;
			$select .= '<option value="'.$tpl.'" '.$selected.'>'.$templatename.'</option>';
		}
	}
	$select .= '</select></span>';
	if(defined('DT_ADMIN')) $select .= '&nbsp;&nbsp;<a href="javascript:tpl_edit(\''.$file.'\', \''.$module.'\', '.$destoon_tpl_id.');" class="t">'.$L['post_edit'].'</a> &nbsp;<a href="javascript:tpl_add(\''.$file.'\', \''.$module.'\');" class="t">'.$L['post_new'].'</a>';
	return $select;
}

/**
 * 会员组下拉选择
 * @param string $name
 * @param string $title
 * @param string $groupid
 * @param string $extend
 * @return string
 */
function group_select($name = 'groupid', $title = '', $groupid = '', $extend = '') {
	global $GROUP;
	if(!$GROUP) $GROUP = PCache::read('group.php');
	$select = '<select name="'.$name.'" '.$extend.'><option value="0">'.$title.'</option>';
	foreach($GROUP as $k=>$v) {
		$select .= '<option value="'.$k.'"'.($k == $groupid ? ' selected' : '').'>'.$v['groupname'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 会员组多选
 * @param string $name
 * @param string $checked
 * @param string $except
 * @return string
 */
function group_checkbox($name = 'groupid', $checked = '', $except = '1,2,4') {
	global $GROUP, $L;
	$GROUP or $GROUP = PCache::read('group.php');
	$checked = $checked ? explode(',', $checked) : array();
	$except = $except ? explode(',', $except) : array();
	$str = $sp = '';
	$id = str_replace(array('[', ']'), array('', ''), $name);
	foreach($GROUP as $k=>$v) {
		if(in_array($k, $except)) continue;
		$sp = in_array($k, $checked) ? ' checked' : '';
		$str .= '<input type="checkbox" name="'.$name.'" value="'.$k.'"'.$sp.' id="'.$id.$k.'"/><label for="'.$id.$k.'"> '.$v['groupname'].'&nbsp; </label>';
	}
	return '<span id="group_'.$id.'">'.$str.'</span>&nbsp;<a href="javascript:check_box(\'group_'.$id.'\', true);">'.$L['select_all'].'</a> / <a href="javascript:check_box(\'group_'.$id.'\', false);">'.$L['clear_all'].'</a>';
}

/**
 * 模块多选
 * @param string $name
 * @param string $checked
 * @param string $except
 * @return string
 */
function module_checkbox($name = 'moduleid', $checked = '', $except = '1,2,3,4') {
	global $MODULE;
	$checked = $checked ? explode(',', $checked) : array();
	$except = $except ? explode(',', $except) : array();
	$str = $sp = '';
	$id = str_replace(array('[', ']'), array('', ''), $name);
	foreach($MODULE as $k=>$v) {
		if(in_array($k, $except) || $v['islink']) continue;
		$sp = in_array($k, $checked) ? ' checked' : '';
		$str .= '<li><input type="checkbox" name="'.$name.'" value="'.$k.'"'.$sp.' id="'.$id.$k.'"/><label for="'.$id.$k.'"> '.$v['name'].'&nbsp; </label></li>';
	}
	return '<ul class="mods">'.$str.'</ul>';
}

/**
 * 模块下拉列表选择
 * @param string $name
 * @param string $title
 * @param string $moduleid
 * @param string $extend
 * @param string $except
 * @return string
 */
function module_select($name = 'moduleid', $title = '', $moduleid = '', $extend = '', $except = '1,2,3') {
	global $MODULE, $L;
	$except = $except ? explode(',', $except) : array();
	$title or $title = $L['choose'];
	$select = '<select name="'.$name.'" '.$extend.'><option value="0">'.$title.'</option>';
	foreach($MODULE as $k=>$v) {
		if(in_array($k, $except) || $v['islink']) continue;
		$select .= '<option value="'.$k.'"'.($k == $moduleid ? ' selected' : '').'>'.$v['name'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 评论模块下拉列表选择
 * @param string $name
 * @param string $title
 * @param string $moduleid
 * @param string $mod
 * @return string
 */
function review_select($name = 'moduleid', $title = '', $moduleid = '', $mod = '') {
	global $MODULE, $L;
	$mod = $mod ? explode(',', $mod) : array();
	$title or $title = $L['choose'];
	$select = '<select name="'.$name.'" ><option value="0">'.$title.'</option>';
	foreach($MODULE as $k=>$v) {
		if(!in_array($k, $mod) || $v['islink']) continue;
		$select .= '<option value="'.$k.'"'.($k == $moduleid ? ' selected' : '').'>'.$v['name'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 主页模版选择
 * @param        $name
 * @param string $title
 * @param int    $groupid
 * @param int    $itemid
 * @param string $extend
 * @return string
 */
function homepage_select($name, $title = '', $groupid = 0, $itemid = 0, $extend = '') {
	global $db, $L;
	$title or $title = $L['choose'];
	$select = '<select name="'.$name.'" '.$extend.'><option value="0">'.$title.'</option>';
	$result = $db->query("SELECT * FROM {$db->getPre()}style ORDER BY listorder DESC,itemid DESC");
	while($r = $db->fetchArray($result)) {
		$select .= '<option value="'.$r['itemid'].'"'.($r['itemid'] == $itemid ? ' selected' : '').'>'.$r['title'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 产品选择
 * @param string $name
 * @param string $title
 * @param int    $pid
 * @param string $extend
 * @return string
 */
function product_select($name = 'pid', $title = '', $pid = 0, $extend = '') {
	global $PRODUCT;
	$PRODUCT or $PRODUCT = PCache::read('product.php');
	$select = '<select name="'.$name.'" '.$extend.'>';
	if($title) $select .= '<option value="0">'.$title.'</option>';
	foreach($PRODUCT as $k=>$v) {
		$select .= '<option value="'.$k.'"'.($k == $pid ? ' selected' : '').'>'.$v['title'].'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 类别下拉选择
 * @param string $name
 * @param string $title
 * @param int    $catid
 * @param int    $moduleid
 * @param string $extend
 * @return string
 */
function category_select($name = 'catid', $title = '', $catid = 0, $moduleid = 1, $extend = '') {
	$option = PCache::read('catetree-'.$moduleid.'.php', '', true);
	if($option) {
		if($catid) $option = str_replace('value="'.$catid.'"', 'value="'.$catid.'" selected', $option);
		$select = '<select name="'.$name.'" '.$extend.' id="catid_1">';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		$select .= $option ? $option : '</select>';
		return $select;
	} else {
		return ajax_category_select($name, $title, $catid, $moduleid, $extend);
	}
}

function XD_Auto_category_select($name = 'catid', $title = '', $catid = 0, $moduleid = 1, $extend = ' id="catid_1" ') {
	$option = PCache::read('catetree-'.$moduleid.'.php', '', true);
	if($option) {
		if($catid) $option = str_replace('value="'.$catid.'"', 'value="'.$catid.'" selected', $option);
		$select = '<select name="'.$name.'" '.$extend.' >';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		$select .= $option ? $option : '</select>';
		return $select;
	} else {
		return ajax_category_select($name, $title, $catid, $moduleid, $extend);
	}
}

/**
 * 类别下拉选择
 * @param string $name
 * @param string $title
 * @param int    $catid
 * @param int    $moduleid
 * @param string $extend
 * @return string
 */
function brand_select($name = 'bid', $title = '', $bid = 0, $moduleid = 1, $extend = '') {
	$option = PCache::read('brandtree.php', '', true);
	if($option) {
		if($bid) $option = str_replace('value="'.$bid.'"', 'value="'.$bid.'" selected', $option);
		$select = '<select name="'.$name.'" '.$extend.' id="brand_1">';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		$select .= $option ? $option : '</select>';
		return $select;
	} else {
		return ajax_brand_select($name, $title, $catid, $moduleid, $extend);
	}
}

/**
 * 分类联动选择
 * @param string $name
 * @param string $title
 * @param int    $catid
 * @param int    $moduleid
 * @param string $extend
 * @param int    $deep
 * @return string
 */
function ajax_brand_select($name = 'bid', $title = '', $bid = 0, $moduleid = 1, $extend = '', $deep = 0) {
	global $brand_id;
	if($brand_id) {
		$brand_id++;
	} else {
		$brand_id = 1;
	}
	$bid = intval($bid);
	$deep = intval($deep);
	$select = '';
	$select .= '<input name="'.$name.'" id="bid_'.$brand_id.'" type="hidden" value="'.$bid.'"/>';
	$select .= '<span id="load_category_'.$brand_id.'">'.get_brand_select($title, $bid, $moduleid, $extend, $deep, $brand_id).'</span>';
	$select .= '<script type="text/javascript">';
	if($brand_id == 1) $select .= 'var brand_moduleid = new Array;';
	$select .= 'brand_moduleid['.$brand_id.']="'.$moduleid.'";';
	if($brand_id == 1) $select .= 'var brand_title = new Array;';
	$select .= 'brand_title['.$brand_id.']=\''.$title.'\';';
	if($brand_id == 1) $select .= 'var category_extend = new Array;';
	$select .= 'brand_extend['.$brand_id.']=\''.$extend.'\';';
	if($brand_id == 1) $select .= 'var brand_brandid = new Array;';
	$select .= 'brand_bid['.$brand_id.']=\''.$bid.'\';';
	if($brand_id == 1) $select .= 'var brand_deep = new Array;';
	$select .= 'brand_deep['.$brand_id.']=\''.$deep.'\';';
	$select .= '</script>';
	if($cat_id == 1) $select .= '<script type="text/javascript" src="'.SITE_URL.'file/script/brand.js"></script>';
	return $select;
}


/**
 * 获取类别选择
 * @param string $title
 * @param int    $catid
 * @param int    $moduleid
 * @param string $extend
 * @param int    $deep
 * @param int    $cat_id
 * @return string
 * @author 耿帅
 * @deprecated
 */
function get_category_select($title = '', $catid = 0, $moduleid = 1, $extend = '', $deep = 0, $cat_id = 1) {
	global $db, $_child;
	$_child or $_child = array();
	$parents = array();
	if($catid) {
		$r = $db->getOne("SELECT child,arrparentid FROM {$db->getPre()}category WHERE catid=$catid");
		$parents = explode(',', $r['arrparentid']);
		if($r['child']) $parents[] = $catid;
	} else {
		$parents[] = 0;
	}
	$select = '';
	foreach($parents as $k=>$v) {
		if($deep && $deep <= $k) break;
		$select .= '<select onchange="load_category(this.value, '.$cat_id.');" '.$extend.'>';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		$condition = $v ? "parentid=$v" : "moduleid=$moduleid AND parentid=0";
		$result = $db->query("SELECT catid,catname FROM {$db->getPre()}category WHERE $condition ORDER BY listorder,catid ASC");
		while($c = $db->fetchArray($result)) {
			$selectid = isset($parents[$k+1]) ? $parents[$k+1] : $catid;
			$selected = $c['catid'] == $selectid ? ' selected' : '';
			if($_child && !in_array($c['catid'], $_child)) continue;
			$select .= '<option value="'.$c['catid'].'"'.$selected.'>'.$c['catname'].'</option>';
		}
		$select .= '</select> ';
	}
	return $select;
}

function get_brand_select($title = '', $bid = 0, $moduleid = 1, $extend = '', $deep = 0, $brand_id = 1) {
	global $db, $_child;
	$_child or $_child = array();
	$parents = array();
	if($bid) {
		$r = $db->getOne("SELECT child,arrparentid FROM {$db->getPre()}brand WHERE id=$bid");
		$parents = explode(',', $r['arrparentid']);
		if($r['child']) $parents[] = $catid;
	} else {
		$parents[] = 0;
	}
	$select = '';
	foreach($parents as $k=>$v) {
		if($deep && $deep <= $k) break;
		$select .= '<select onchange="load_brand(this.value, '.$brand_id.');" '.$extend.'>';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		$condition = $v ? "parentid=$v" : "  parentid=0";
		$result = $db->query("SELECT id,name FROM {$db->getPre()}brand WHERE $condition ORDER BY listorder,id ASC");
		while($c = $db->fetchArray($result)) {
			$selectid = isset($parents[$k+1]) ? $parents[$k+1] : $catid;
			$selected = $c['id'] == $selectid ? ' selected' : '';
			if($_child && !in_array($c['id'], $_child)) continue;
			$select .= '<option value="'.$c['id'].'"'.$selected.'>'.$c['name'].'</option>';
		}
		$select .= '</select> ';
	}
	return $select;
}


/**
 * 分类联动选择
 * @param string $name
 * @param string $title
 * @param int    $catid
 * @param int    $moduleid
 * @param string $extend
 * @param int    $deep
 * @return string
 */
function ajax_category_select($name = 'catid', $title = '', $catid = 0, $moduleid = 1, $extend = '', $deep = 0) {
	global $cat_id;
	if($cat_id) {
		$cat_id++;
	} else {
		$cat_id = 1;
	}
	$catid = intval($catid);
	$deep = intval($deep);
	$select = '';
	$select .= '<input name="'.$name.'" id="catid_'.$cat_id.'" type="hidden" value="'.$catid.'"/>';
	$select .= '<span id="load_category_'.$cat_id.'">'.get_category_select($title, $catid, $moduleid, $extend, $deep, $cat_id).'</span>';
	$select .= '<script type="text/javascript">';
	if($cat_id == 1) $select .= 'var category_moduleid = new Array;';
	$select .= 'category_moduleid['.$cat_id.']="'.$moduleid.'";';
	if($cat_id == 1) $select .= 'var category_title = new Array;';
	$select .= 'category_title['.$cat_id.']=\''.$title.'\';';
	if($cat_id == 1) $select .= 'var category_extend = new Array;';
	$select .= 'category_extend['.$cat_id.']=\''.$extend.'\';';
	if($cat_id == 1) $select .= 'var category_catid = new Array;';
	$select .= 'category_catid['.$cat_id.']=\''.$catid.'\';';
	if($cat_id == 1) $select .= 'var category_deep = new Array;';
	$select .= 'category_deep['.$cat_id.']=\''.$deep.'\';';
	$select .= '</script>';
	if($cat_id == 1) $select .= '<script type="text/javascript" src="'.SITE_URL.'file/script/category.js"></script>';
	return $select;
}

/**
 * 获取分类的名称
 * @param int $catid
 * @return mixed
 */
function get_category_name($catid = 0) {
	global $db;
	$r = $db->getOne("SELECT catname FROM {$db->getPre()}category WHERE catid=$catid");
	$categoryname=$r['catname'];
	return $categoryname;
}

/**
 * 从缓存中获取分类的名称
 * @param int  $moduleid
 * @param int $catid
 * @return mixed
 */
function get_cache_category_name($moduleid,$catid = 0) {
	$company = PCache::read('category-'.$moduleid.'.php');
	return $company[$catid]['catname'];
}
/**
 * 获取区域选择
 * @param string $title
 * @param int    $areaid
 * @param string $extend
 * @param int    $deep
 * @param int    $id
 * @return string
 */
function get_area_select($title = '', $areaid = 0, $extend = '', $deep = 0, $id = 1, $moduleid) {
	global $db, $AREA;
	$auth = xd_areaAuth($moduleid);
	$pid = isset($AREA[$areaid]) ? $AREA[$areaid]['parentid'] : 0;
	$parents = array();
	if($areaid) {
		$r = $db->getOne("SELECT child,arrparentid FROM {$db->getPre()}area WHERE areaid=$areaid");
		$parents = explode(',', $r['arrparentid']);
		if($r['child']) $parents[] = $areaid;
	} else {
		$parents[] = 0;
	}
	$select = '';
	foreach($parents as $k=>$v) {
		if($deep && $deep <= $k) break;
		$v = intval($v);
		if ($auth>0) {
			// 5代表当前的4层级菜单
			if (($auth + $k) <5) {
				$authExt =  ' disabled="disabled" ';
			} else {
				$authExt = '';
			}
		}
		$select .= '<select id="area'.$k.'" onchange="load_area(this.value, '.$id.');" '.$extend . $authExt . '>';
		if($title) $select .= '<option value="'.$pid.'">'.$title.'</option>';
		$result = $db->query("SELECT areaid,areaname FROM {$db->getPre()}area WHERE parentid=$v ORDER BY listorder,areaid ASC");
		while($a = $db->fetchArray($result)) {
			$selectid = isset($parents[$k+1]) ? $parents[$k+1] : $areaid;
			$selected = $a['areaid'] == $selectid ? ' selected' : '';
			$select .= '<option value="'.$a['areaid'].'"'.$selected.'>'.$a['areaname'].'</option>';
		}
		$select .= '</select> ';
	}
	return $select;
}

/**
 * 获取区域名称
 * @param int $areaid
 * @return mixed
 */
function get_area_name($areaid = 0) {
	global $db;
	$r = $db->getOne("SELECT areaname FROM {$db->getPre()}area WHERE areaid=$areaid");
	$areaname=$r['areaname'];
	return $areaname;
}

function get_area_select_jump($title = '', $areaid = 0, $extend = '', $deep = 0, $id = 1) {
	global $db;
	$parents = array();
	if($areaid) {
		$r = $db->getOne("SELECT child,arrparentid FROM {$db->getPre()}area WHERE areaid=$areaid");
		$parents = explode(',', $r['arrparentid']);
		if($r['child']) $parents[] = $areaid;
	} else {
		$parents[] = 0;
	}
	$select = '';
	foreach($parents as $k=>$v) {
		if($deep && $deep <= $k) break;
		$v = intval($v);
		$select .= '<select id="area'.$k.'" onchange="'."GoAndChang('areaid'".",this.value".');"'.$extend.'>';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		$result = $db->query("SELECT areaid,areaname FROM {$db->getPre()}area WHERE parentid=$v ORDER BY listorder,areaid ASC");
		while($a = $db->fetchArray($result)) {
			$selectid = isset($parents[$k+1]) ? $parents[$k+1] : $areaid;
			$selected = $a['areaid'] == $selectid ? ' selected' : '';
			$select .= '<option value="'.$a['areaid'].'"'.$selected.'>'.$a['areaname'].'</option>';
		}
		$select .= '</select> ';
	}
	return $select;
}

/**
 * 显示地区列表并点击跳转
 * @param string $name		下拉菜单名称
 * @param string $title		默认显示（第一项）显示内容
 * @param string $areaid	现选择的地区id
 * @param string $extend	扩展
 * @param string $deep		
 * @author Sameal
 * @return string  */
function ajax_area_select_jump($name = 'areaid', $title = '', $areaid = 0, $extend = '', $deep = 0) {
	global $area_id;
	if($area_id) {
		$area_id++;
	} else {
		$area_id = 1;
	}
	$areaid = intval($areaid);
	$deep = intval($deep);
	$select = '';
	$select .= '<input name="'.$name.'" id="areaid_'.$area_id.'" type="hidden" value="'.$areaid.'"/>';
	$select .= '<span id="load_area_'.$area_id.'">'.get_area_select_jump($title, $areaid, $extend, $deep, $area_id).'</span>';
	$select .= '<script type="text/javascript">';
	if($area_id == 1) $select .= 'var area_title = new Array;';
	$select .= 'area_title['.$area_id.']=\''.$title.'\';';
	if($area_id == 1) $select .= 'var area_extend = new Array;';
	$select .= 'area_extend['.$area_id.']=\''.$extend.'\';';
	if($area_id == 1) $select .= 'var area_areaid = new Array;';
	$select .= 'area_areaid['.$area_id.']=\''.$areaid.'\';';
	if($area_id == 1) $select .= 'var area_deep = new Array;';
	$select .= 'area_deep['.$area_id.']=\''.$deep.'\';';
	$select .= '</script>';
	if($area_id == 1) $select .= '<script type="text/javascript" src="'.SITE_URL.'file/script/area.js"></script>';
	return $select;
}

/**
 * 地区选择的联动
 * @param string $name
 * @param string $title
 * @param int    $areaid
 * @param string $extend
 * @param int    $deep
 * @return string
 */
function ajax_area_select($name = 'areaid', $title = '', $areaid = 0, $extend = '', $deep = 0, $moduleid='') {
	global $area_id;
	if($area_id) {
		$area_id++;
	} else {
		$area_id = 1;
	}
	$areaid = intval($areaid);
	$deep = intval($deep);
	$select = '';
	$select .= '<input name="'.$name.'" id="areaid_'.$area_id.'" type="hidden" value="'.$areaid.'"/>';
	$select .= '<span id="load_area_'.$area_id.'">'.get_area_select($title, $areaid, $extend, $deep, $area_id, $moduleid).'</span>';
	$select .= '<script type="text/javascript">';
	if($area_id == 1) $select .= 'var area_title = new Array;';
	$select .= 'area_title['.$area_id.']=\''.$title.'\';';
	if($area_id == 1) $select .= 'var area_extend = new Array;';
	$select .= 'area_extend['.$area_id.']=\''.$extend.'\';';
	if($area_id == 1) $select .= 'var area_areaid = new Array;';
	$select .= 'area_areaid['.$area_id.']=\''.$areaid.'\';';
	if($area_id == 1) $select .= 'var area_deep = new Array;';
	$select .= 'area_deep['.$area_id.']=\''.$deep.'\';';
	if ($moduleid) {
		$select .= 'area_moduleid=\''.$moduleid.'\';';
	} else {
		$select .= 'area_moduleid=0;';
	}

	$select .= '</script>';
	if($area_id == 1) $select .= '<script type="text/javascript" src="'.SITE_URL.'file/script/area.js"></script>';
	return $select;
}

/**
 * 级别选择
 * @param        $name      表单名
 * @param string $title     默认的显示状态
 * @param int    $level     默认的选中级别
 * @param string $extend    扩展
 * @return string 级别选择, 分析模块中的级别,然后进行selection选择
 */
function level_select($name, $title = '', $level = 0, $extend = '') {
	global $MOD, $L;
	$names = isset($MOD['level']) && $MOD['level'] ? $MOD['level'] : '';
	$names = $names ? explode('|', trim($names)) : array();
	$select = '<select name="'.$name.'" '.$extend.'>';
	if($title) $select .= '<option value="0">'.$title.'</option>';
	for($i = 1; $i < 10; $i++) {
		$n = isset($names[$i-1]) ? ' '.$names[$i-1] : '';
		$select .= '<option value="'.$i.'"'.($i == $level ? ' selected' : '').'>'.$i.' '.$L['level'].$n.'</option>';
	}
	$select .= '</select>';
	return $select;
}

/**
 * 检测是否 url
 * @param $url
 * @return int
 */
function is_url($url) {
	return preg_match("/^[http|https]\:\/\/[a-z0-9\/\.\#\&\?\;\,]{4,}$/", $url);
}

/**
 * 检测是否url
 * @param $email
 * @return bool
 */
function is_email($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

/**
 * 检测是否是手机
 * @param $mobile
 * @return int
 */
function is_mobile($mobile) {
	return preg_match("/^[0-9]{7,}$/", $mobile);
}

/**
 * 联系方式
 * @param $telephone
 * @return int
 */
function is_telephone($telephone) {
	return preg_match("/^[0-9\-\+]{7,}$/", $telephone);
}

/**
 * 检测是否gbk编码
 * @param $string
 * @return int
 */
function is_gbk($string) {
	return preg_match("/^([\s\S]*?)([\x81-\xfe][\x40-\xfe])([\s\S]*?)/", $string);
}

/**
 * @param        $date
 * @param string $sep
 * @return bool 检测是否是标准时间.
 */
function is_date($date, $sep = '-') {
	// 时间为空
	if(empty($date)) return false;
	// 长度大于 10
	if(strlen($date) > 10)  return false;
	list($year, $month, $day) = explode($sep, $date);
	return checkdate($month, $day, $year);
}

/**
 * 检测是否是图片
 * @param $file
 * @return int
 */
function is_image($file) {
	return preg_match("/^(jpg|jpeg|gif|png|bmp)$/i", File::ext($file));
}

/**
 * 是否是系统存在的用户
 * @param $username
 * @return bool
 */
function is_user($username) {
	global $db;
	$r = $db->getOne("SELECT username FROM {$db->getPre()}member WHERE username='$username'");
	return $r ? true : false;
}

/**
 * 检测密码是否符合
 * @param $username
 * @param $password
 * @return bool
 */
function is_password($username, $password) {
	global $db;
	if(strlen($password) < 6) return false;
	$r = $db->getOne("SELECT password FROM {$db->getPre()}member WHERE username='$username'");
	if(!$r) return false;
	return $r['password'] == (Utils::isMd5($password) ? md5($password) : md5(md5($password)));
}

/**
 * 检测支付密码
 * @param $username
 * @param $payword
 * @return bool
 */
function is_payword($username, $payword) {
	global $db;
	if(strlen($payword) < 6) return false;
	$r = $db->getOne("SELECT payword,password FROM {$db->getPre()}member WHERE username='$username'");
	if(!$r) return false;
	$r['payword'] = $r['payword'] ? $r['payword'] : $r['password'];
	return $r['payword'] == (Utils::isMd5($payword) ? md5($payword) : md5(md5($payword)));
}


/**
 * 检测是否是用户名
 * @param $file
 * @return int
 */
function match_userid($file) {
	$file = basename($file);
	if(preg_match("/\-([0-9]{2}+)\-([0-9]{1,}+)\./", $file, $m)) {
		return $m[2];
	} else {
		return 0;
	}
}

/**
 * @param $content
 * @return mixed 使用正则表达式清空链接.
 */
function clear_link($content) {
	$content = preg_replace("/<a[^>]*>/i", "", $content);
	return preg_replace("/<\/a>/i", "", $content); 
}

/**
 * @param        $content
 * @param string $ext
 * @param int    $self
 * @return mixed 将远程的图片保存到本地
 */
function save_remote($content, $ext = 'jpg|jpeg|gif|png|bmp|swf', $self = 0) {
	global $DT, $DT_TIME, $MODULE, $moduleid, $_userid;
	if(!$_userid || !$content) return $content;
	if(!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return $content;
	require_once DT_INC.'/image.class.php';
	$dftp = false;
	if($DT['ftp_remote'] && $DT['remote_url']) {
		require_once DT_INC.'/dftp.class.php';
		$ftp = new dftp($DT['ftp_host'], $DT['ftp_user'], $DT['ftp_pass'], $DT['ftp_port'], $DT['ftp_path'], $DT['ftp_pasv'], $DT['ftp_ssl']);
		$dftp = $ftp->connected;
	}
	$urls = $oldpath = $newpath = array();
	$DT['uploaddir'] or $DT['uploaddir'] = 'Ym/d';
	foreach($matches[2] as $k=>$url) {
		if(in_array($url, $urls)) continue;
		$urls[$url] = $url;		
		if(strpos($url, '://') === false) continue;
		if(!$self) {
			if(DT_DOMAIN) {
				if(strpos($url, '.'.DT_DOMAIN.'/') !== false) continue;
			} else {
				if(strpos($url, SITE_URL) !== false) continue;
			}
		}
		//if(match_userid($url) == $_userid) continue;
		$filedir = 'file/upload/'.timetodate($DT_TIME, $DT['uploaddir']).'/';
		$filepath = SITE_URL.$filedir;
		$fileroot = DT_ROOT.'/'.$filedir;
		$file_ext = File::ext($url);
		$filename = timetodate($DT_TIME, 'H-i-s').'-'.rand(10, 99).'-'.$_userid.'.'.$file_ext;
		$newfile = $fileroot.$filename;
		if(file_copy($url, $newfile)) {
			if(is_image($newfile)) {
				if(!@getimagesize($newfile)) {
					File::del($newfile);
					continue;
				}
				if($DT['water_type']) {
					$image = new image($newfile);
					if($DT['water_type'] == 2) {
						$image->waterimage();
					} else if($DT['water_type'] == 1) {
						$image->watertext();
					}
				}
			}
			$oldpath[] = $url;
			$newurl = linkurl($filepath.$filename, 1);
			if($dftp) {
				$exp = explode("file/upload/", $newurl);
				if($ftp->dftp_put($filedir.$filename, $exp[1])) {
					$newurl = $DT['remote_url'].$exp[1];
					File::del($newfile);
				}
			}
			$newpath[] = $newurl;
		}
	}
	unset($matches);
	return str_replace($oldpath, $newpath, $content);
}

/**
 * 保存缩略图
 * @param     $content
 * @param     $no
 * @param int $width
 * @param int $height
 * @return string
 */
function save_thumb($content, $no, $width = 120, $height = 90) {
	global $DT, $DT_TIME, $_userid;
	if(!$_userid || !$content) return '';
	$ext = 'jpg|jpeg|gif|png|bmp';
	if(!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return '';
	require_once DT_INC.'/image.class.php';
	$dftp = false;
	if($DT['ftp_remote'] && $DT['remote_url']) {
		require_once DT_INC.'/dftp.class.php';
		$ftp = new dftp($DT['ftp_host'], $DT['ftp_user'], $DT['ftp_pass'], $DT['ftp_port'], $DT['ftp_path'], $DT['ftp_pasv'], $DT['ftp_ssl']);
		$dftp = $ftp->connected;
	}
	$urls = $oldpath = $newpath = array();
	$DT['uploaddir'] or $DT['uploaddir'] = 'Ym/d';
	foreach($matches[2] as $k=>$url) {
		if($k == $no - 1) {
			$filedir = 'file/upload/'.timetodate($DT_TIME, $DT['uploaddir']).'/';
			$filepath = SITE_URL.$filedir;
			$fileroot = DT_ROOT.'/'.$filedir;
			$file_ext = File::ext($url);
			$filename = timetodate($DT_TIME, 'H-i-s').'-'.rand(10, 99).'-'.$_userid.'.'.$file_ext;
			$newfile = $fileroot.$filename;
			if(file_copy($url, $newfile)) {
				if(is_image($newfile)) {					
					if(!@getimagesize($newfile)) {
						File::del($newfile);
						return '';
					}
					$image = new image($newfile);
					$image->thumb($width, $height);
				}
				$newurl = linkurl($filepath.$filename, 1);
				if($dftp) {
					$exp = explode("file/upload/", $newurl);
					if($ftp->dftp_put($filedir.$filename, $exp[1])) {
						$newurl = $DT['remote_url'].$exp[1];
						File::del($newfile);
					}
				}
				return $newurl;
			}
		}
	}
	unset($matches);
	return '';
}

/**
 * 删除本地?
 *
 * @param        $content
 * @param        $userid
 * @param string $ext
 */
function delete_local($content, $userid, $ext = 'jpg|jpeg|gif|png|bmp|swf') {
	if(preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) {
		foreach($matches[2] as $url) {
			PictureUpload::deletePicture($url, $userid);
		}
		unset($matches);
	}
}

/**
 * 对比并且删除不同的文件
 * @param        $new
 * @param        $old
 * @param string $ext 删除内容中不同的图片
 */
function delete_diff($new, $old, $ext = 'jpg|jpeg|gif|png|bmp|swf') {
	global $_userid;
	$new = stripslashes($new);
	$diff_urls = $new_urls = $old_urls = array();
	if(preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $old, $matches)) {
		foreach($matches[2] as $url) {
			$old_urls[] = $url;
		}
	} else {
		return;
	}
	if(preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $new, $matches)) {
		foreach($matches[2] as $url) {
			$new_urls[] = $url;
		}
	}
	foreach($old_urls as $url) {
		in_array($url, $new_urls) or $diff_urls[] = $url;
	}
	if(!$diff_urls) return;
	foreach($diff_urls as $url) {
		PictureUpload::deletePicture($url, $_userid);
	}
	unset($new, $old, $matches, $url, $diff_urls, $new_urls, $old_urls);
}

/**
 * 清空上传
 * @param string $content
 * @param int    $itemid
 */
function clear_upload($content = '', $itemid = 0) {
	global $CFG, $DT, $db, $_userid;
	Session::start();
	if(!isset($_SESSION['uploads']) || !$_SESSION['uploads'] || !$content) return;
	$update = array();
	foreach($_SESSION['uploads'] as $file) {
		if(strpos($content, $file) === false) {
			PictureUpload::deletePicture($file, $_userid);
		} else {
			if($DT['uploadlog'] && $itemid) $update[] = "'".md5($file)."'";
		}
	}
	if($update) $db->query("UPDATE {$db->getPre()}upload_".($_userid%10)." SET itemid=$itemid WHERE item IN (".implode(',', $update).")");
	$_SESSION['uploads'] = array();
}

/**
 *
 * @param $period
 * @return bool
 */
function check_period($period) {
	global $DT_TIME;
	if($period) {
		if(strpos($period, ',') === false) {
			$period = explode('|', $period);
			foreach($period as $p) {
				$p = str_replace(':', '.', $p);
				$p = explode('-', $p);
				$f = $p[0];
				$t = $p[1];
				$n = date('G.i', $DT_TIME);
				if(($f > $t && ($n > $f || $n < $t)) || ($f < $t && $n > $f && $n < $t)) return true;
			}
			return false;
		} else {
			return strpos(','.$period.',', ','.date('w', $DT_TIME).',') === false ? false : true;
		}
	} else {
		return false;
	}
}

/**
 * 获取状态
 * @param $status
 * @param $check
 * @return int
 */
function get_status($status, $check) {
	global $DT;
	if(!$check && $DT['check_week'] && check_period($DT['check_week'])) $check = true;
	if(!$check && $DT['check_hour'] && check_period($DT['check_hour'])) $check = true;
	if($status == 0) {
		return 0;
	} else if($status == 1) {
		return 2;
	} else if($status == 2) {
		return 2;
	} else if($status == 3) {
		return $check ? 2 : 3;
	} else if($status == 4) {
		return $check ? 2 : 3;
	} else {
		return 2;
	}
}

/**
 * 重新加载 captcha
 * @return string
 */
function reload_captcha() {
	return 'try{parent.reloadcaptcha();}catch(e){}';
}

/**
 * 重新加载问题
 * @return string
 */
function reload_question() {
	return 'try{parent.reloadquestion();}catch(e){}';
}
?>